package com.chb.test;

import com.chb.utils.ESClient;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.BoostingQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;

/**
 * 复合查询
 */
public class CompoundQueryDemo {
    RestHighLevelClient client = ESClient.getClient();
    String index = "sms-logs-index";



    @Test
    public void boostingQuery() throws IOException {
        // 1、创建SearchRequest
        SearchRequest searchRequest = new SearchRequest(index);

        // 2、指定查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoostingQueryBuilder boostingQueryBuilder = QueryBuilders.boostingQuery(
                QueryBuilders.matchQuery("smsContent", "魅力"),
                QueryBuilders.matchQuery("smsContent", "传媒")
                ).negativeBoost(0.2f);

        searchSourceBuilder.query(boostingQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        // 3、执行
        SearchResponse resp = client.search(searchRequest, RequestOptions.DEFAULT);

        // 4、输出
        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }


    @Test
    public void boolQuery() throws IOException {
        // 1、创建SearchRequest对象
        SearchRequest request = new SearchRequest(index);

        // 2、指定查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 2.1、查询城市为北京或者杭州
        boolQueryBuilder.should(QueryBuilders.termQuery("province", "北京"));
        boolQueryBuilder.should(QueryBuilders.termQuery("province", "杭州"));
        // 2.2、运营商id不等于2的
        boolQueryBuilder.mustNot(QueryBuilders.termQuery("opratorId", 2));
        // 2.3、smsContent中包含魅力或者推动的公司的短信内容；
        boolQueryBuilder.must(QueryBuilders.matchQuery("smsContent", " 魅力 推动"));

        searchSourceBuilder.query(boolQueryBuilder);
        request.source(searchSourceBuilder);


        // 3、执行查询
        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);

        // 4、输出结果
        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

}
